import React, { useState, useEffect, useMemo } from 'react';
import { Quiz, AppView, ExamResult, MistakeNotebook, Question, MistakeQuestion } from '../types';
import { generateQuiz, generateQuizFromMistakes } from './services/aiService';
import {
  getHistory,
  saveQuizToHistory,
  deleteQuizFromHistory,
  getMistakeNotebooks,
  addQuestionToNotebook
} from './services/storageService';
import {
  QuizGenerator,
  SettingsModal,
  ConfirmModal,
  QuizListSidebar
} from './components';
import { AddToMistakeModal } from './components/AddToMistakeModal';
import {
  HomeView,
  ExamPreviewView,
  ExamRunningView,
  ResultView,
  MistakeNotebookView
} from './views';
import { useTimer } from './hooks/useTimer';
import { calculateScore, sortQuestionsByType } from './utils/scoreCalculator';

export default function App() {
  // --- State ---
  const [view, setView] = useState<AppView>('HOME');
  const [inputTopic, setInputTopic] = useState('');
  const [currentQuiz, setCurrentQuiz] = useState<Quiz | null>(null);
  const [userAnswers, setUserAnswers] = useState<Map<string, string | string[]>>(new Map());
  const [quizHistory, setQuizHistory] = useState<Quiz[]>([]);
  const [mistakeNotebooks, setMistakeNotebooks] = useState<MistakeNotebook[]>([]);
  const [currentNotebook, setCurrentNotebook] = useState<MistakeNotebook | null>(null);
  const [activeQuestionIndex, setActiveQuestionIndex] = useState(0);
  const [isSettingsOpen, setIsSettingsOpen] = useState(false);
  const [isAddToMistakeOpen, setIsAddToMistakeOpen] = useState(false);
  const [questionToAdd, setQuestionToAdd] = useState<Question | null>(null);

  // Timer hook
  const { elapsedTime, resetTimer, formatTime } = useTimer(view === 'EXAM_RUNNING');

  // Confirm Modal State
  const [confirmConfig, setConfirmConfig] = useState({
    isOpen: false,
    title: '',
    message: '',
    onConfirm: () => {}
  });

  // Load history on mount
  useEffect(() => {
    setQuizHistory(getHistory());
    setMistakeNotebooks(getMistakeNotebooks());
  }, []);

  const showConfirm = (title: string, message: string, onConfirm: () => void) => {
    setConfirmConfig({ isOpen: true, title, message, onConfirm });
  };

  // --- Actions ---
  const handleGenerate = async (topic: string = inputTopic) => {
    if (!topic.trim()) return;
    setView('GENERATING');
    try {
      const quiz = await generateQuiz(topic);
      setCurrentQuiz(quiz);
      saveQuizToHistory(quiz);
      setQuizHistory(getHistory());
      setView('EXAM_PREVIEW');
    } catch (error) {
      console.error(error);
      setView('HOME');
      setTimeout(() => alert('生成失败: 请检查 API Key 设置或网络连接'), 100);
    }
  };

  const handleGenerateFromMistakes = async (questions: MistakeQuestion[], notebookName: string) => {
    if (questions.length === 0) return;
    setInputTopic(`${notebookName} 题集`);
    setView('GENERATING');
    try {
      const quiz = await generateQuizFromMistakes(questions);
      setCurrentQuiz(quiz);
      saveQuizToHistory(quiz);
      setQuizHistory(getHistory());
      setView('EXAM_PREVIEW');
    } catch (error) {
      console.error(error);
      setView('MISTAKE_NOTEBOOK');
      setTimeout(() => alert('生成失败: 请检查 API Key 设置或网络连接'), 100);
    }
  };

  const startExam = () => {
    setUserAnswers(new Map());
    resetTimer();
    setActiveQuestionIndex(0);
    setView('EXAM_RUNNING');
  };

  const submitExam = () => {
    showConfirm('提交试卷', '确定要提交试卷吗？提交后将无法修改答案。', () => {
      setConfirmConfig((prev) => ({ ...prev, isOpen: false }));
      finishExam();
    });
  };

  const finishExam = () => {
    if (!currentQuiz) return;

    const scoreData = calculateScore(currentQuiz.questions, userAnswers);

    // Save result to history
    const result: ExamResult = {
      score: scoreData.score,
      total: scoreData.total,
      correct: scoreData.correct,
      timestamp: Date.now(),
      userAnswers: Object.fromEntries(userAnswers)
    };

    const updatedQuiz = { ...currentQuiz, latestResult: result };
    setCurrentQuiz(updatedQuiz);
    saveQuizToHistory(updatedQuiz);
    setQuizHistory(getHistory());

    setView('RESULT');
  };

  const handleHomeClick = () => {
    if (view === 'EXAM_RUNNING') {
      showConfirm('退出考试', '确定要退出吗？当前考试进度将丢失。', () => {
        setConfirmConfig((prev) => ({ ...prev, isOpen: false }));
        setView('HOME');
      });
    } else {
      setView('HOME');
    }
  };

  const handleAnswer = (qId: string, value: string, isMulti: boolean) => {
    setUserAnswers((prev) => {
      const newMap = new Map(prev);
      if (isMulti) {
        const current = (newMap.get(qId) as string[]) || [];
        if (current.includes(value)) {
          newMap.set(
            qId,
            current.filter((v) => v !== value)
          );
        } else {
          newMap.set(qId, [...current, value]);
        }
      } else {
        newMap.set(qId, value);
      }
      return newMap;
    });
  };

  const loadHistoryQuiz = (quiz: Quiz) => {
    const sortedQuestions = sortQuestionsByType(quiz.questions);
    setCurrentQuiz({ ...quiz, questions: sortedQuestions });
    setUserAnswers(new Map());
    resetTimer();
    setActiveQuestionIndex(0);
    setView('EXAM_PREVIEW');
  };

  const loadMistakeNotebook = (notebook: MistakeNotebook) => {
    setCurrentNotebook(notebook);
    setView('MISTAKE_NOTEBOOK');
  };

  const viewHistoryResult = (e: React.MouseEvent, quiz: Quiz) => {
    e.stopPropagation();
    if (!quiz.latestResult) return;

    const sortedQuestions = sortQuestionsByType(quiz.questions);
    setCurrentQuiz({ ...quiz, questions: sortedQuestions });
    const answersMap = new Map(Object.entries(quiz.latestResult.userAnswers));
    setUserAnswers(answersMap);
    setActiveQuestionIndex(0);
    setView('RESULT');
  };

  const handleDeleteQuiz = (quiz: Quiz) => {
    deleteQuizFromHistory(quiz.id);
    setQuizHistory(getHistory());
    setView('HOME');
  };

  const handleUpdateQuiz = (updatedQuiz: Quiz) => {
    setCurrentQuiz(updatedQuiz);
    saveQuizToHistory(updatedQuiz);
    setQuizHistory(getHistory());
  };

  const handleAddToMistakeClick = (question: Question) => {
    setQuestionToAdd(question);
    setIsAddToMistakeOpen(true);
  };

  const handleAddToMistakeConfirm = (notebookId: string) => {
    if (questionToAdd) {
      addQuestionToNotebook(notebookId, questionToAdd);
      setMistakeNotebooks(getMistakeNotebooks());
      setQuestionToAdd(null);
    }
  };

  const refreshNotebooks = () => {
    setMistakeNotebooks(getMistakeNotebooks());
    // Also refresh current notebook if it's open
    if (currentNotebook) {
      const updated = getMistakeNotebooks().find(n => n.id === currentNotebook.id);
      if (updated) {
        setCurrentNotebook(updated);
      }
    }
  };

  // --- Calculations ---
  const scoreData = useMemo(() => {
    if (!currentQuiz) {
      return { score: 0, total: 0, correct: 0, wrong: 0, results: [] };
    }
    return calculateScore(currentQuiz.questions, userAnswers);
  }, [currentQuiz, userAnswers]);

  // --- Sidebar Content ---
  const sidebarContent = (
    <QuizListSidebar
      quizHistory={quizHistory}
      mistakeNotebooks={mistakeNotebooks}
      currentQuiz={currentQuiz}
      currentNotebookId={currentNotebook?.id}
      view={view}
      onLoadQuiz={loadHistoryQuiz}
      onViewResult={viewHistoryResult}
      onLoadNotebook={loadMistakeNotebook}
    />
  );

  // --- Main Render ---
  return (
    <>
      {view === 'GENERATING' && <QuizGenerator topic={inputTopic} />}
      
      {view === 'HOME' && (
        <HomeView
          inputTopic={inputTopic}
          onInputChange={setInputTopic}
          onGenerate={handleGenerate}
          onSettingsClick={() => setIsSettingsOpen(true)}
          onHomeClick={handleHomeClick}
          sidebarContent={sidebarContent}
        />
      )}

      {view === 'EXAM_PREVIEW' && currentQuiz && (
        <ExamPreviewView
          quiz={currentQuiz}
          onStartExam={startExam}
          onBack={() => setView('HOME')}
          onViewResult={viewHistoryResult}
          onDelete={handleDeleteQuiz}
          onUpdateQuiz={handleUpdateQuiz}
          onSettingsClick={() => setIsSettingsOpen(true)}
          onHomeClick={handleHomeClick}
          sidebarContent={sidebarContent}
        />
      )}

      {view === 'EXAM_RUNNING' && currentQuiz && (
        <ExamRunningView
          quiz={currentQuiz}
          activeQuestionIndex={activeQuestionIndex}
          userAnswers={userAnswers}
          isReview={false}
          elapsedTime={elapsedTime}
          onAnswer={handleAnswer}
          onSubmit={submitExam}
          onHomeClick={handleHomeClick}
          onQuestionChange={setActiveQuestionIndex}
          onSettingsClick={() => setIsSettingsOpen(true)}
          onAddToMistake={handleAddToMistakeClick}
          formatTime={formatTime}
          sidebarContent={sidebarContent}
        />
      )}

      {view === 'RESULT' && (
        <ResultView
          scoreData={scoreData}
          onHomeClick={handleHomeClick}
          onReview={() => {
            setActiveQuestionIndex(0);
            setView('REVIEW');
          }}
        />
      )}

      {view === 'REVIEW' && currentQuiz && (
        <ExamRunningView
          quiz={currentQuiz}
          activeQuestionIndex={activeQuestionIndex}
          userAnswers={userAnswers}
          isReview={true}
          scoreData={scoreData}
          onAnswer={handleAnswer}
          onSubmit={submitExam}
          onHomeClick={handleHomeClick}
          onBackToResult={() => setView('RESULT')}
          onQuestionChange={setActiveQuestionIndex}
          onSettingsClick={() => setIsSettingsOpen(true)}
          onAddToMistake={handleAddToMistakeClick}
          formatTime={formatTime}
          sidebarContent={sidebarContent}
        />
      )}

      {view === 'MISTAKE_NOTEBOOK' && currentNotebook && (
        <MistakeNotebookView
          notebook={currentNotebook}
          onHomeClick={handleHomeClick}
          onSettingsClick={() => setIsSettingsOpen(true)}
          sidebarContent={sidebarContent}
          onNotebookUpdate={refreshNotebooks}
          onNotebookDelete={() => {
            refreshNotebooks();
            setView('HOME');
          }}
          onGenerateFromMistakes={(questions) => handleGenerateFromMistakes(questions, currentNotebook.name)}
        />
      )}

      <SettingsModal isOpen={isSettingsOpen} onClose={() => setIsSettingsOpen(false)} />
      
      <AddToMistakeModal
        isOpen={isAddToMistakeOpen}
        onClose={() => setIsAddToMistakeOpen(false)}
        onAdd={handleAddToMistakeConfirm}
      />

      <ConfirmModal
        isOpen={confirmConfig.isOpen}
        title={confirmConfig.title}
        message={confirmConfig.message}
        onConfirm={confirmConfig.onConfirm}
        onCancel={() => setConfirmConfig((prev) => ({ ...prev, isOpen: false }))}
      />
    </>
  );
}